/****************************************************
          File Name:server.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Fri 12 Sep 2014 08:19:22 PM CST
*****************************************************/

#include "msg.h"
#include <string.h>
#include <signal.h>
#include <fcntl.h>

void dealing(int sig)
{
	int msgid;
	
	if((msgid=msgget(key,S_IRUSR))==-1)
		err("msgget in signal handler");
	if(msgctl(msgid,IPC_RMID,NULL)==-1)
		err("remove");
	exit(0);
}

int main(int argc,char *argv[])
{
	struct sigaction act;
	struct msgbuf msg;
	int msgid,i=0;
	int perm=S_IWUSR|S_IRUSR|S_IWGRP;
	
	msg.mtype=1;
	
	if((msgid=msgget(key,perm|IPC_CREAT))==-1)
	{
		if(errno != EEXIST)
			err("msgget");
	}
	
	if(sigemptyset(&act.sa_mask)==-1)
		err("sigemptyset");
	act.sa_flags=0;
	act.sa_handler=dealing;
	
	if(sigaction(SIGINT,&act,NULL)==-1)		// set a signal handler fot signal 2 to do clean jobs
		err("sigaction");
	
	for(;;)
	{
		i++;
		if(msgrcv(msgid,&msg,DATA_SIZE,0,0)==-1)	// not use IPC_NOWAIT, so this will block
			err("msgrcv");
		if(strcpy(msg.mtext,"send from server\n")==NULL)
			err("strcpy");
		if(msgsnd(msgid,&msg,strlen(msg.mtext),0)==-1)
			err("msgsnd");
	}
	
	exit(0);
}
